﻿using System;
using System.Xml.Linq;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.YouTube
{
    public static class YouTubeExtensions
    {
        #region YouTube

        public static YouTubeVideo ToYouTubeVideo(this XElement el)
        {
            return new YouTubeVideo
            {
                Id = GetIdFromUrl(el.Element("guid").Value),
                Url = el.Element("link").Value,
                Title = el.Element("title").Value,
                ThumbnailLarge = string.Format("http://img.youtube.com/vi/{0}/0.jpg", GetIdFromUrl(el.Element("guid").Value)),
                ThumbnailSmall1 = string.Format("http://img.youtube.com/vi/{0}/1.jpg", GetIdFromUrl(el.Element("guid").Value)),
                ThumbnailSmall2 = string.Format("http://img.youtube.com/vi/{0}/2.jpg", GetIdFromUrl(el.Element("guid").Value)),
                ThumbnailSmall3 = string.Format("http://img.youtube.com/vi/{0}/3.jpg", GetIdFromUrl(el.Element("guid").Value)),
                Published = DateTime.Parse(el.Element("pubDate").Value),
                Author = el.Element("author").Value
            };
        }

        private static string GetIdFromUrl(string url)
        {
            return url.Substring(url.LastIndexOf(':') + 1);
        }

        #endregion

        #region UMP

        public static MediaItem ToMediaItem(this YouTubeVideo video)
        {
            var mi = new MediaItem
            {
                Id = video.Id,
                Title = video.Title,
                Icon = "youTubeMedia.png",
                HasChildren = false,
                PreviewImageUrl = video.ThumbnailSmall1,
                Selectable = true
            };

            mi.MetaData.Add("Published", video.Published.ToShortDateString());
            mi.MetaData.Add("Author", video.Author);

            return mi;
        }

        #endregion
    }
}